package com.happe.foodeasy.manage.controller.linkimg;

import com.alibaba.fastjson.JSON;
import com.happe.foodeasy.manage.common.entity.ManagerEntity;
import com.happe.foodeasy.manage.controller.CommonIdentifyKeyInModelAndView;
import com.happe.foodeasy.manage.controller.ManagerLoginOnController;
import com.happe.foodeasy.manage.dto.PositionImageDTO;
import com.happe.foodeasy.manage.helper.RetrieveDataHelper;
import com.happe.foodeasy.manage.service.LinkImageStatusService;
import com.happe.foodeasy.manage.service.PositionImageService;
import com.happe.foodeasy.manage.service.PositionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 该类用于操作位置图片
 * Created by wubin on 2016-09-06.
 */
@Controller
@RequestMapping("/positionImage")
public class PositionImageController {
    private Logger logger = LoggerFactory.getLogger(PositionImageController.class);
    private static final String SUCCESS_MESSAGE = "保存成功";
    private static final String DEFEAT_MESSAGE = "保存失败";
    private static final String ALL_POSITION_LIST = "allPosition";

    @Resource
    private RetrieveDataHelper retrieveDataHelper;
    @Resource
    private LinkImageStatusService linkImageStatusService;
    @Resource
    private PositionImageService positionImageService;
    @Resource
    private PositionService positionService;

    @RequestMapping("/storeLinkImage")
    public ModelAndView storeLinkImage(MultipartFile linkImage, PositionImageDTO positionImageDTO, HttpServletRequest request) {
        String message;
        ModelAndView modelAndView = new ModelAndView("linkImg/linkImageSaveResult");
        positionImageDTO.setInsertManagerId(getInsertManagerId(request));
        positionImageDTO.setInsertTime(new Date());
        try {
            initPositionImage(positionImageDTO, linkImage);
            positionImageService.storePositionImage(positionImageDTO);
            message = SUCCESS_MESSAGE;
        } catch (IOException e) {
            logger.error(e.getMessage());
            message = DEFEAT_MESSAGE;
        }

        modelAndView.addObject("message", message);
        return modelAndView;
    }

    @RequestMapping("/enterLinkImageManage")
    public ModelAndView enterLinkImageManage(long position, long status) {
        ModelAndView modelAndView = new ModelAndView("linkImg/linkImageManage");
        modelAndView.addObject(CommonIdentifyKeyInModelAndView.ALL_NAV_DIRECTORY_KEY, retrieveDataHelper.retrieveAllNavDirectory());
        modelAndView.addObject(CommonIdentifyKeyInModelAndView.TARGET_SELECT_NAV_KEY, "链接图片管理");
        modelAndView.addObject(ALL_POSITION_LIST, positionService.retrieveAllPosition());
        modelAndView.addObject("allLinkImageStatus", linkImageStatusService.retrieveAllStatus());
        //根据提供的position和status，查找相应的positionImage
        modelAndView.addObject("targetPositionImage", positionImageService.selectByPositionAndStatus(position, status));

        //添加这两个Object用于标识当前选中的菜单项
        modelAndView.addObject("positionId", position);
        modelAndView.addObject("statusId", status);
        return modelAndView;
    }

    /**
     * 根据positionId获取特定位置的正在使用图片的信息
     *
     * @param positionId 特定的位置Id
     * @param response   HttpServletResponse
     */
    @RequestMapping("/retrievePositionImageInfo")
    public void retrieveImageInfo(Integer positionId, HttpServletResponse response) {
        List<PositionImageDTO> results = positionImageService.selectByPositionAndStatus(positionId, 1);
        String jsonResult = JSON.toJSONString(results);
        try {
            response.getWriter().write(jsonResult);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 用于返回imageId参数指定的位置图片
     *
     * @param imageId  具体的在数据库存的图片的id
     * @param response httpServletResponse
     */
    @ResponseBody
    @RequestMapping(value = "/retrieveTargetPositionImage", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] retrieveTargetPositionImage(long imageId, HttpServletResponse response) {
        PositionImageDTO result = positionImageService.selectTargetByteById(imageId);
        return result.getPhotoByte();
    }

    private void initPositionImage(PositionImageDTO positionImageDTO, MultipartFile linkImage) throws IOException {
        positionImageDTO.setLinkImageStatusId(2);
        positionImageDTO.setPhotoName(linkImage.getOriginalFilename());
        positionImageDTO.setPhotoByte(linkImage.getBytes());
        positionImageDTO.setValidFlag("0");
    }

    private long getInsertManagerId(HttpServletRequest request) {
        ManagerEntity currentManager = (ManagerEntity) request.getSession().getAttribute(ManagerLoginOnController.LOGIN_MANAGER_FLAG);
        return currentManager.getId();
    }
}
